package com.rjwh.dingdong.client.fragment.menu;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.community.CommunityPostDetailActivity;
import com.rjwh.dingdong.client.activity.community.CommunityPostDigestActivity;
import com.rjwh.dingdong.client.activity.mathgame.MathGameDetailActivity;
import com.rjwh.dingdong.client.activity.mathgame.MathGameIslandsListActivity;
import com.rjwh.dingdong.client.activity.mathgame.MathGameMyTracksActivity;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.adapter.DrawBookTopicAdapter;
import com.rjwh.dingdong.client.adapter.MathGameHomeGvAdapter;
import com.rjwh.dingdong.client.adapter.MathGamePopListAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.DrawBookMainPageTopic;
import com.rjwh.dingdong.client.bean.localbean.LocalGmaeInfo;
import com.rjwh.dingdong.client.bean.localbean.MathBookMenuData;
import com.rjwh.dingdong.client.bean.localbean.MathGameHomeGameItemData;
import com.rjwh.dingdong.client.bean.localbean.MathGameMathBook;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.MathGamePresenter;
import com.rjwh.dingdong.client.mvp.view.MathGameView;
import com.rjwh.dingdong.client.service.HttpWebCoreService;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.PicPathUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.ToastUtil;
import com.rjwh.dingdong.client.util.UtilPublic;
import com.rjwh.dingdong.client.view.NoScrollListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * @author Kay
 * @ClassName MathGameFragment
 * @Description 数学游戏主页
 * @date 2016-6-13
 * @history 2016-6-13 author: description:
 */
public class MathGameFragment extends BaseFragment implements AdapterView.OnItemClickListener, MathGameView {

    @BindView(R.id.maths_game_topic_list)
    NoScrollListView mathsGameTopicList;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.maths_game_title_view)
    RelativeLayout mathsGameTitleView;
    @BindView(R.id.maths_game_title_right_img)
    ImageView mathsGameTitleRightImg;
    @BindView(R.id.maths_game_banner_img)
    ImageView mathsGameBannerImg;
    @BindView(R.id.maths_game_my_tracks_games_gv)
    GridView mathsGameMyTracksGamesGv;
    @BindView(R.id.maths_game_quality_games_gv)
    GridView mathsGameQualityGamesGv;
    @BindView(R.id.maths_game_title_txt)
    TextView mathsGameTitleTxt;
    @BindView(R.id.maths_game_my_tracks_root)
    RelativeLayout mathsGameMyTracksRoot;
    @BindView(R.id.math_game_mPullRefreshView)
    SwipyRefreshLayout mathGameMPullRefreshView;

    private DrawBookTopicAdapter topicAdapter;
    private MathGamePresenter presenter;
    private String bookid;
    private List<MathBookMenuData> bookmenulist = new ArrayList<>();
    private String bookname;
    private MathGameHomeGvAdapter myTracksGvAdapter;
    private MathGameHomeGvAdapter qualityGvAdapter;
    private Observable<Integer> observable;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.math_game_home_layout, container, false);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        hideErrorView();
        showLoadingView();
        startObserver();
        presenter = new MathGamePresenter(getActivity(), this);
        doGetMathGamekMainPage("0");
    }

    private void startObserver() {
        observable = RxBus.get().register(LocalConstant.RX__POST_LOGIN_UPDATE_UI, Integer.class);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                               @Override
                               public void call(Integer type) {
                                   doGetMathGamekMainPage(bookid);
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   LogUtil.d("MathGameFragment", throwable.getMessage());
                               }
                           }
                );
    }

    private void doGetMathGamekMainPage(String bookid) {
        presenter.doGetMathGameMainPage(bookid);
    }

    private void initView() {
        mathsGameTopicList.setFocusable(false);// 解决进入界面不定位到顶部
        mathsGameMyTracksGamesGv.setFocusable(false);
        mathsGameQualityGamesGv.setFocusable(false);

        topicAdapter = new DrawBookTopicAdapter(getActivity());
        mathsGameTopicList.setAdapter(topicAdapter);
        mathsGameTopicList.setOnItemClickListener(this);

        myTracksGvAdapter = new MathGameHomeGvAdapter(getContext());
        qualityGvAdapter = new MathGameHomeGvAdapter(getContext());
        mathsGameMyTracksGamesGv.setAdapter(myTracksGvAdapter);
        mathsGameQualityGamesGv.setAdapter(qualityGvAdapter);
        mathsGameMyTracksGamesGv.setOnItemClickListener(new MyGVonItemClickListener());
        mathsGameQualityGamesGv.setOnItemClickListener(new MyGVonItemClickListener());
        mathGameMPullRefreshView.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction == SwipyRefreshLayoutDirection.TOP) {
                    doGetMathGamekMainPage(bookid);
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DrawBookMainPageTopic item = (DrawBookMainPageTopic) parent.getAdapter().getItem(position);
        if (item != null) {
            String linkurl = item.getFilepath();
            Intent intent = new Intent(getActivity(), CommunityPostDetailActivity.class);
            String url = linkurl + "?userid=" + MyApplication.spUtil.getStrPreferenceByParamName(getActivity(), LocalConstant.SP_USERID) + "&platform=ANDROID" + "&version=" + MyApplication.versionCode + "&udid=" + MyApplication.deviceId + "&babyid=" + MyApplication.spUtil.getStrPreferenceByParamName(getActivity(), LocalConstant.SP_BABYID) + "&token=" + MyApplication.spUtil.getStrPreferenceByParamName(getActivity(), LocalConstant.SP_USER_TOKEN);
            String topicid = item.getTopicid();
            if (item.getImage() != null && !item.getImage().isEmpty()) {
                intent.putExtra("sharepic", PicPathUtil.getPicUrl(item.getImage().get(0)));
            }
            intent.putExtra("url", url);
            intent.putExtra("topicid", topicid);
            startActivity(intent);
        }
    }

    public class MyGVonItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MathGameHomeGvAdapter adapter = (MathGameHomeGvAdapter) parent.getAdapter();
            MathGameHomeGameItemData item = adapter.getItem(position);
            String bookid = item.getBookid();
            String lessonid = item.getLessonid();
            String gamedir = item.getGamedir();
            String gameid = item.getGameid();
            if (AsStrUtils.isEmpty(bookid) || AsStrUtils.isEmpty(lessonid) || AsStrUtils.isEmpty(gamedir) || AsStrUtils.isEmpty(gameid)) {
                ToastUtil.showToast(getContext(), getContext().getString(R.string.game_not_existed));
                return;
            }
            if (isGameNotNull(bookid)) {
                File file = new File(FileUtils.getGameDirectory(), bookid + "/" + gamedir);
                if (file.isDirectory() && file.listFiles().length > 0) {
                    LogUtil.e("MyGVonItemClickListener", file.getPath());
                    String userid = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_USERID);
                    String babyid = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_BABYID);
                    String token = MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_USER_TOKEN);
                    String uuid = MyApplication.deviceId;
                    String version = MyApplication.versionCode;
                    String url = String.format(HttpWebCoreService.GAME_ITEM_URL, bookid, gamedir, userid,
                            babyid, version, uuid, token, System.currentTimeMillis(), bookid, lessonid, gamedir, gameid);
                    OaGameActivity.startActivity(getContext(), url);
                } else {
                    ToastUtil.showToast(getContext(), getContext().getString(R.string.game_filepath_error));
                }
            } else {
                // 进入游戏详情
                MathGameDetailActivity.startActivity(getContext(), bookid);
            }
        }

    }

    private boolean isGameNotNull(String bookid) {
        boolean result = false;
        List<LocalGmaeInfo> localGmaeInfoList = MyApplication.db.findAllByWhere(LocalGmaeInfo.class, "pid=" + bookid + " and type=2");
        if (!localGmaeInfoList.isEmpty()) {
            result = true;
        }
        return result;
    }

    @OnClick({R.id.maths_game_title_right_img, R.id.btn_refresh, R.id.maths_game_tab_my_tracks_more_btn, R.id.maths_game_tab_quality_games_more_btn, R.id.maths_game_tab_topic_more_arrow})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.maths_game_title_right_img:
                //游戏岛选择框
                showIslandSelectPopWD(bookmenulist);
                break;
            case R.id.btn_refresh:
                hideErrorView();
                showLoadingView();
                doGetMathGamekMainPage(bookid);
                break;
            case R.id.maths_game_tab_my_tracks_more_btn:
                // 跳转我的足迹
                MathGameMyTracksActivity.startActivity(getContext(), bookid, "MathGameFragment");
                break;
            case R.id.maths_game_tab_quality_games_more_btn:
                // 跳转精品游戏
                MathGameIslandsListActivity.startActivity(getContext(), Integer.parseInt(bookid), bookname, "MathGameFragment");
                break;
            case R.id.maths_game_tab_topic_more_arrow:
                // 跳转社区精华列表
                CommunityPostDigestActivity.startActivity(getContext(), LocalConstant.MODULARTYPE_MATH);
                break;
        }
    }

    private void showIslandSelectPopWD(List<MathBookMenuData> bookmenulist) {
        View mPopWindowView = getActivity().getLayoutInflater().inflate(R.layout.math_game_popupwindow, null);
        // Focusable 为True，PopupWindow的点击事件才会相应
        final PopupWindow mPopWindow = new PopupWindow(mPopWindowView, UtilPublic.dp2px(132, getContext()), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 必须在代码中设置一下背景色，点击外面不会隐藏此弹窗
        mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // Focusable 为False时，不执行则点击外面不会隐藏此弹窗
        mPopWindow.setOutsideTouchable(true);
        //设置动画效果
        mPopWindow.setAnimationStyle(R.style.popmenu_anim_style);

        // 显示在View的正下方,设置偏移量来调整位置
        mPopWindow.showAsDropDown(mathsGameTitleView, mathsGameTitleView.getWidth() - mPopWindow.getWidth() - UtilPublic.dp2px(8, getContext()), 0);

        ListView poplist = (ListView) mPopWindowView.findViewById(R.id.mathgame_pop_list_lv);
        MathGamePopListAdapter adapter = new MathGamePopListAdapter(getContext());
        poplist.setAdapter(adapter);
        poplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPopWindow.dismiss();
                MathBookMenuData item = (MathBookMenuData) parent.getAdapter().getItem(position);
                String bookmenuid = item.getBookmenuid();
                bookname = item.getBookmenuname();
                if (!bookid.equals(bookmenuid)) {
                    hideErrorView();
                    showLoadingView();
                    doGetMathGamekMainPage(bookmenuid);
                }
            }
        });
        adapter.appendToList(bookmenulist);
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void LoadData(MathGameMathBook mathBook, List<MathBookMenuData> bookmenulist, List<MathGameHomeGameItemData> footsteplist, List<MathGameHomeGameItemData> goodgamelist, List<DrawBookMainPageTopic> topiclist) {

        final String bookid = mathBook.getBookid();
        String bannerurl = mathBook.getBannerurl();
        String bookname = mathBook.getBookname();

        //更新标题
        if (!AsStrUtils.isEmpty(bookname)) {
            mathsGameTitleTxt.setText(bookname);
            this.bookname = bookname;
        }
        this.bookid = bookid;

        Glide.with(this).load(bannerurl)
                .dontAnimate()
                .placeholder(R.drawable.icon_pic_holder)
                .error(R.drawable.icon_pic_holder)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(mathsGameBannerImg);
        mathsGameBannerImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MathGameDetailActivity.startActivity(getContext(), bookid);
            }
        });

        //设置右上角菜单
        if (!bookmenulist.isEmpty()) {
            mathsGameTitleRightImg.setVisibility(View.VISIBLE);
            this.bookmenulist = bookmenulist;
        }
        //更新GridView视图
        if (footsteplist.isEmpty()) {
            //我的足迹数据为空时隐藏视图
            mathsGameMyTracksGamesGv.setVisibility(View.GONE);
            mathsGameMyTracksRoot.setVisibility(View.GONE);
        } else {
            mathsGameMyTracksGamesGv.setVisibility(View.VISIBLE);
            mathsGameMyTracksRoot.setVisibility(View.VISIBLE);
            myTracksGvAdapter.setStarShowed(true);
            myTracksGvAdapter.clearAll();
            myTracksGvAdapter.appendToList(footsteplist);
        }
        if (goodgamelist.isEmpty()) {
            mathsGameQualityGamesGv.setVisibility(View.GONE);
        } else {
            mathsGameQualityGamesGv.setVisibility(View.VISIBLE);
            qualityGvAdapter.setStarShowed(false);
            qualityGvAdapter.clearAll();
            qualityGvAdapter.appendToList(goodgamelist);
        }

        //设置帖子数据
        topicAdapter.clear();
        topicAdapter.appendToList(topiclist);
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        mathGameMPullRefreshView.setRefreshing(isRefresh);
    }

    @Override
    public void onPlaybackServiceBound(PlaybackService mPlaybackService) {

    }

    @Override
    public void onPlaybackServiceUnbound() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        RxBus.get().unregister(LocalConstant.RX__POST_LOGIN_UPDATE_UI, observable);
    }
}
